package com.huaxin.hxmodulesystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaxin.hxmodulesystem.common.MyMetaObjectHandler;
import com.huaxin.hxmodulesystem.common.UserContext;
import com.huaxin.hxmodulesystem.dto.ResponseCode;
import com.huaxin.hxmodulesystem.dto.ResponseResult;
import com.huaxin.hxmodulesystem.dto.request.AddFamilyReqDTO;
import com.huaxin.hxmodulesystem.dto.request.UpdateFamilyReqDTO;
import com.huaxin.hxmodulesystem.dto.response.GetFamilyListRespDTO;
import com.huaxin.hxmodulesystem.mapper.FamilyMapper;
import com.huaxin.hxmodulesystem.mapper.UserMapper;
import com.huaxin.hxmodulesystem.mapping.FamilyMapping;
import com.huaxin.hxmodulesystem.models.Family;
import com.huaxin.hxmodulesystem.models.User;
import com.huaxin.hxmodulesystem.service.FamilyService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class FamilyServiceImpl extends ServiceImpl<FamilyMapper, Family> implements FamilyService {
    private final ApplicationContext applicationContext;
    private final FamilyMapping familyMapping;
    private final CacheManager cacheManager;
    private final UserMapper userMapper;
    private final MyMetaObjectHandler myMetaObjectHandler;

    /**
     * 添加家庭
     *
     * @param in
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class) // 明确指定回滚所有异常
    public ResponseResult<String> addFamily(AddFamilyReqDTO in) {
        if (in == null || StringUtils.isBlank(in.getName())) {
            return ResponseResult.parameterError(null, "家庭名称不能为空");
        }

        String currentUserId = UserContext.getCurrentUserId();
        if (StringUtils.isBlank(currentUserId)) {
            return ResponseResult.parameterError(null, "无法获取当前用户信息");
        }
        Family family = familyMapping.toEntity(in);

        // 初始化家庭成员列表，将创建者加入
        // 使用 Set 确保成员唯一性，避免重复
        Set<String> memberSet = new HashSet<>();
        memberSet.add(currentUserId); // 创建者自动成为成员
        family.setFamilyMembers(String.join(",", memberSet));
        boolean saveFamilySuccess = this.save(family);
        if (!saveFamilySuccess) {
            return ResponseResult.failure(ResponseCode.INTERNAL_ERROR, "创建家庭失败，请稍后再试！", null);
        }
        User user = new User();
        user.setId(currentUserId);
        user.setFamilyId(family.getId());
        int updateResult = userMapper.updateById(user);
        if (updateResult <= 0) {
            throw new RuntimeException("更新用户家庭信息失败，用户ID: " + currentUserId);
        }
        return ResponseResult.ok(family.getId());
    }

    /**
     * 修改家庭
     *
     * @param in
     * @return
     */
    @Override
    public ResponseResult<String> updateFamily(UpdateFamilyReqDTO in) {
        if (in == null) {
            return ResponseResult.parameterError(null, "参数错误");
        }
        if (StringUtils.isBlank(in.getId())) {
            return ResponseResult.parameterError(null, "参数错误");
        }
        Family entity = this.getById(in.getId());
        familyMapping.updateEntity(in, entity);
        if (this.updateById(entity)) {
            return ResponseResult.ok(null);
        } else {
            return ResponseResult.failure(ResponseCode.INTERNAL_ERROR, "修改家庭失败，请稍后再试！", null);
        }
    }


    /**
     * 删除家庭
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult<String> deleteFamily(String id) {
        if (StringUtils.isBlank(id)) {
            return ResponseResult.parameterError(null, "家庭ID不能为空");
        }
        Family family = this.baseMapper.selectById(id);
        if (family == null) {
            return ResponseResult.failure(ResponseCode.INTERNAL_ERROR, "家庭不存在", null);
        }
        if (applicationContext.getBean(FamilyService.class).removeById(id)) {
            // 手动清除缓存
            org.springframework.cache.Cache userInfoCache = cacheManager.getCache("familyInfo");
            if (userInfoCache != null) {
                userInfoCache.evict(family.getName());
            }
            return ResponseResult.ok(null);
        } else {
            return ResponseResult.failure(ResponseCode.INTERNAL_ERROR, "删除家庭失败！", null);
        }
    }

    /**
     * 获取家庭列表
     *
     * @param userId 用户ID
     * @return
     */
    @Override
    public ResponseResult<GetFamilyListRespDTO> getFamilyTheUserList(String userId) {

        QueryWrapper<Family> wrapper = new QueryWrapper<>();
        wrapper.like("family_members", userId);
        Family family = this.baseMapper.selectOne(wrapper);
        if (family == null) {
            return ResponseResult.failure(ResponseCode.NOT_FOUND, "未找到该用户对应的家庭", null);
        }
        GetFamilyListRespDTO getFamilyListRespDTO = familyMapping.toDTO(family);
        User adminUser = userMapper.selectById(userId);
        if (adminUser != null) {
            getFamilyListRespDTO.setAdminUserName(adminUser.getNickname());
        }
        if (family.getFamilyMembers() != null && family.getFamilyMembers().length() > 0) {
            List<String> familyMemberIds = Arrays.asList(family.getFamilyMembers().split(","));
            List<User> familyMembers = userMapper.selectBatchIds(familyMemberIds);
            getFamilyListRespDTO.setUsers(familyMembers);
        }
        return ResponseResult.ok(getFamilyListRespDTO);
    }

    /**
     * 获取家庭列表
     *
     * @param pageNum
     * @param pageSize
     * @param name
     * @return
     */
    @Override
    public ResponseResult<Page<Family>> getFamilyList(Integer pageNum, Integer pageSize, String name) {
        Page<Family> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Family> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(name)) {
            wrapper.like(Family::getName, name);
        }
        return ResponseResult.ok(this.baseMapper.selectPage(page, wrapper));
    }

    /**
     * 添加家庭成员
     *
     * @param userId
     * @param familyId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult<String> addFamilyMember(String userId, String familyId) {
        if (StringUtils.isBlank(userId)) {
            return ResponseResult.parameterError(null, "用户ID不能为空");
        }
        if (StringUtils.isBlank(familyId)) {
            return ResponseResult.parameterError(null, "家庭ID不能为空");
        }
        Family family = this.baseMapper.selectById(familyId);
        if (family == null) {
            return ResponseResult.notFound(null, "没有找到该家庭");
        }
        Set<String> memberSet = new HashSet<>();
        // 如果已有成员，先添加进去
        if (StringUtils.isNotBlank(family.getFamilyMembers())) {
            // 使用逗号分割，过滤掉可能的空字符串
            memberSet.addAll(Arrays.stream(family.getFamilyMembers().split(","))
                    .map(String::trim)
                    .filter(StringUtils::isNotBlank)
                    .collect(Collectors.toList()));
        }
        boolean memberAdded = memberSet.add(userId); // add 方法返回 true 表示是新添加的
        if (!memberAdded) {
            // 可以选择返回一个"已存在"的状态码，或者像现在这样返回成功
            return ResponseResult.ok("用户已是家庭成员，无需重复添加！");
        }
        family.setFamilyMembers(String.join(",", memberSet));
        boolean updateFamilySuccess = this.baseMapper.updateById(family) > 0;
        if (!updateFamilySuccess) {
            return ResponseResult.failure(ResponseCode.INTERNAL_ERROR, "更新家庭成员列表失败，请稍后再试！", null);
        }
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在，无法添加为家庭成员。用户ID: " + userId);
        }
        if (!Objects.equals(user.getFamilyId(), familyId)) {
            user.setFamilyId(familyId);
            int updateResult = userMapper.updateById(user);
            if (updateResult <= 0) {
                throw new RuntimeException("更新用户家庭信息失败，用户ID: " + userId);
            }
        }
        return ResponseResult.ok("添加成功！");
    }

    /**
     * 移除家庭成员
     *
     * @param userId
     * @param familyId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult<String> removeFamilyMember(String userId, String familyId) {
        if (StringUtils.isBlank(userId)) {
            return ResponseResult.parameterError(null, "用户ID不能为空");
        }
        if (StringUtils.isBlank(familyId)) {
            return ResponseResult.parameterError(null, "家庭ID不能为空");
        }
        Family family = this.baseMapper.selectById(familyId);
        if (family == null) {
            return ResponseResult.notFound(null, "没有找到该家庭");
        }

        Set<String> memberSet = new HashSet<>();
        if (StringUtils.isNotBlank(family.getFamilyMembers())) {
            memberSet.addAll(Arrays.stream(family.getFamilyMembers().split(","))
                    .map(String::trim)
                    .filter(StringUtils::isNotBlank)
                    .collect(Collectors.toList()));
        }
        if (!memberSet.contains(userId)) {
            return ResponseResult.failure(ResponseCode.INTERNAL_ERROR, "用户不是该家庭成员", null);
        }

        boolean memberRemoved = memberSet.remove(userId);
        if (!memberRemoved) {
            return ResponseResult.failure(ResponseCode.INTERNAL_ERROR, "移除成员失败，请稍后再试", null);
        }
        family.setFamilyMembers(String.join(",", memberSet));
        boolean updateFamilySuccess = this.baseMapper.updateById(family) > 0;
        if (!updateFamilySuccess) {
            return ResponseResult.failure(ResponseCode.INTERNAL_ERROR, "更新家庭成员列表失败，请稍后再试！", null);
        }
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在，无法解除家庭关联。用户ID: " + userId);
        }
        if (Objects.equals(user.getFamilyId(), familyId)) {
            user.setFamilyId(null);
            int updateResult = userMapper.updateById(user);
            if (updateResult <= 0) {
                throw new RuntimeException("更新用户家庭信息失败，用户ID: " + userId);
            }
        }
        return ResponseResult.ok("移除成功！");
    }

    /**
     * 获取家庭信息
     *
     * @param familyId 主键id
     * @return
     */
    @Override
    public ResponseResult<Family> getFamilyById(String familyId) {
        if (StringUtils.isBlank(familyId)) {
            return ResponseResult.parameterError(null, "家庭ID不能为空");
        }
        return ResponseResult.ok(this.baseMapper.selectById(familyId));
    }
}
